<template>
  <div
    class="form-item"
    :class="{active: index === activeIndex, asDrag: asDrag}"
    @click.stop="formItemClick"
  >
    <a-form-item
      :colon="itemConfig.type !== 'grid'"
      :name="asDrag ? '' : itemConfig.defaultKey"
      :rules="[
        {
          required: itemConfig.required,
          message: itemConfig.message,
          trigger: 'blur',
          validator: validator
        }
      ]"
    >
      <template #label>
        <span v-if="itemConfig.type !== 'grid'">{{ itemConfig.label }}</span>
      </template>
      <ComItem :item-config="itemConfig"></ComItem>
    </a-form-item>
    <div class="handle" v-if="asDrag">
      <component
        @click.stop="handleCopy"
        is="copy-outlined"
        class="fs-18 pointer mr-5 c-primaryColor"
      ></component>
      <component
        @click.stop="handleDelete"
        is="delete-outlined"
        class="fs-18 pointer"
        style="color: red"
      ></component>
    </div>
  </div>
</template>

<script lang="ts" setup>
import {watch} from "vue";
import ComItem from "./ComItem.vue";

const props = defineProps({
  itemConfig: {
    type: Object,
    default: {}
  },
  index: {
    type: Number,
    default: 0
  },
  activeIndex: {
    type: Number,
    default: null
  },
  asDrag: {
    type: Boolean,
    default: true
  }
});

const emits = defineEmits([
  "update:activeIndex",
  "itemConfigDefaultValueChange",
  "itemDelete",
  "itemCopy"
]);
const formItemClick = () => {
  emits("update:activeIndex", props.index);
};

const validator = (rule, value, callback) => {
  if (rule.required) {
    if (!value || JSON.stringify(value) === "[]") {
      return Promise.reject(rule.message);
    } else {
      return Promise.resolve();
    }
  }
};

const handleDelete = () => {
  emits("itemDelete", props.index);
};

const handleCopy = () => {
  emits("itemCopy", props.index);
};

watch(
  () => props.itemConfig.defaultValue,
  () => {
    emits("itemConfigDefaultValueChange", props.itemConfig);
  },
  {deep: true}
);
</script>

<style lang="less" scoped>
.form-item {
  position: relative;
  border: 2px solid #ffffff;

  .handle {
    position: absolute;
    right: 0;
    bottom: 0;
  }

  &.asDrag {
    &.active {
      border-color: @primary-color;
    }

    :deep(.ant-form-item) {
      &:hover {
        background-color: #ecf5ff;
      }
    }
  }

  :deep(.ant-form-item) {
    margin: 0 !important;
    padding: 0 0 24px 0;
    background-color: #ffffff;

    .ant-form-item-label {
      width: v-bind("props.itemConfig.width");
    }
  }
}
</style>
